<template>

  <div>
    <AppBarPage v-if="!loading && notAuthorized">
      <KPageContainer>
        <AuthMessage
          :authorizedRole="authorizedRole"
          :header="authorizationErrorHeader"
          :details="authorizationErrorDetails"
        />
      </KPageContainer>
    </AppBarPage>

    <AppBarPage v-else-if="!loading && error">
      <KPageContainer>
        <AppError />
      </KPageContainer>
    </AppBarPage>

    <div
      v-else
      tabindex="-1"
      data-test="base-page"
    >
      <slot :loading="loading"></slot>
    </div>

    <GlobalSnackbar />
    <UpdateNotification
      v-if="!loading && showNotification && mostRecentNotification"
      :id="mostRecentNotification.id"
      :title="mostRecentNotification.title"
      :msg="mostRecentNotification.msg"
      :linkText="mostRecentNotification.linkText"
      :linkUrl="mostRecentNotification.linkUrl"
      @submit="dismissUpdateModal"
    />
  </div>

</template>


<script>

  import { mapState } from 'vuex';
  import Lockr from 'lockr';
  import { UPDATE_MODAL_DISMISSED } from 'kolibri/constants';
  import { currentLanguage, defaultLanguage } from 'kolibri/utils/i18n';
  import AuthMessage from 'kolibri/components/AuthMessage';
  import AppBarPage from 'kolibri/components/pages/AppBarPage';
  import AppError from 'kolibri/components/error/AppError';
  import GlobalSnackbar from 'kolibri/components/GlobalSnackbar';
  import useUser from 'kolibri/composables/useUser';
  import PingbackNotificationDismissedResource from './internal/PingbackNotificationDismissedResource';
  import PingbackNotificationResource from './internal/PingbackNotificationResource';
  import UpdateNotification from './internal/UpdateNotification';

  export default {
    name: 'NotificationsRoot',
    components: {
      AppBarPage,
      AppError,
      AuthMessage,
      GlobalSnackbar,
      UpdateNotification,
    },
    setup() {
      const { isAdmin, isSuperuser, currentUserId } = useUser();

      return {
        isAdmin,
        isSuperuser,
        currentUserId,
      };
    },
    props: {
      authorized: {
        type: Boolean,
        required: false,
        default: true,
      },
      authorizedRole: {
        type: String,
        default: null,
      },
      authorizationErrorHeader: {
        type: String,
        default: null,
      },
      authorizationErrorDetails: {
        type: String,
        default: null,
      },
      loading: {
        type: Boolean,
        default: null,
      },
    },
    data() {
      return {
        notifications: [],
        notificationModalShown: true,
      };
    },
    computed: {
      ...mapState({
        error: state => state.core.error,
      }),
      notAuthorized() {
        // catch "not authorized" error, display AuthMessage
        if (
          this.error &&
          this.error.response &&
          this.error.response.status &&
          this.error.response.status == 403
        ) {
          return true;
        }
        return !this.authorized;
      },
      showNotification() {
        if (
          (this.isAdmin || this.isSuperuser) &&
          !Lockr.get(UPDATE_MODAL_DISMISSED) &&
          this.notificationModalShown &&
          this.notifications.length !== 0
        ) {
          return true;
        }
        return false;
      },
      mostRecentNotification() {
        if (this.notifications.length === 0) {
          return null;
        }
        let languageCode = defaultLanguage.id;
        // notifications should already be ordered by timestamp
        const notification = this.notifications[0];
        if (notification) {
          // check if translated message is available for current language
          if (notification.i18n[currentLanguage] !== undefined) {
            languageCode = currentLanguage;
          }
          // i18n data structure generated by nutritionfacts_i18n.py
          return {
            id: notification.id,
            title: notification.i18n[languageCode].title,
            msg: notification.i18n[languageCode].msg,
            linkText: notification.i18n[languageCode].link_text,
            linkUrl: notification.link_url,
          };
        }
        return null;
      },
    },
    created() {
      this.getNotifications();
    },

    methods: {
      async getNotifications() {
        if (this.isAdmin || this.isSuperuser) {
          try {
            const notifications = await PingbackNotificationResource.fetchCollection();
            this.notifications = _notificationListState(notifications);
          } catch (error) {
            this.dispatchError(error);
          }
        }
      },
      async saveDismissedNotification(notificationId) {
        try {
          await PingbackNotificationDismissedResource.saveModel({
            data: {
              user: this.currentUserId,
              notification: notificationId,
            },
          });
          this.removeNotification(notificationId);
        } catch (error) {
          this.dispatchError(error);
        }
      },
      dismissUpdateModal() {
        if (this.notifications.length === 0) {
          this.notificationModalShown = false;
          Lockr.set(UPDATE_MODAL_DISMISSED, true);
        } else {
          this.saveDismissedNotification(this.mostRecentNotification.id);
        }
      },
      dispatchError(error) {
        this.$store.dispatch('handleApiError', { error });
      },
      removeNotification(notificationId) {
        this.notifications = this.notifications.filter(n => n.id !== notificationId);
      },
    },
  };

  function _notificationListState(data) {
    if (!data || data.length === 0) {
      return [];
    }
    return data.map(notification => ({
      id: notification.id,
      version_range: notification.version_range,
      timestamp: notification.timestamp,
      link_url: notification.link_url,
      i18n: notification.i18n,
    }));
  }

</script>


<style lang="scss" scoped></style>
